package com.financing.service.user;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.financing.enums.invest.BidStatus;
import com.financing.model.invest.CouponLog;
import com.financing.model.invest.Repay;
import com.financing.model.invest.Trade;
import com.financing.model.user.User;
import com.financing.service.BaseService;
import com.financing.service.invest.TradeService;
import com.financing.util.AES;
import com.financing.util.DateUtil;
import com.financing.util.Money;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

public class UserService extends BaseService<User>{
	private TradeService trade = new TradeService();

	
	/**
	 * 获取个人信息
	 * @throws Exception 
	 */
	public User getInfo(int userId) throws Exception {
		return this.getInfo(userId, 0);
	}
	
	/**
	 * 获取个人信息
	 * @throws Exception 
	 */
	public User getInfo(int userId, int needAes) throws Exception {
		User u = User.me.findFirst("select * from user where id=?",userId);
		u.refereshAmount(); 
		if(needAes==1) {
			// 敏感信息加密
			u.setMobile(AES.encode(u.getMobile()));
			u.setCertNum(AES.encode(u.getCertNum()));
			u.setBankCard(AES.encode(u.getBankCard()));
			u.setEmail(AES.encode(u.getEmail()));
		}
		return u;
	}


	/**
	 * 根据手机号查找
	 */
	public User findByMobile(String mobile) {
		return User.me.findFirst("select * from user where mobile=?",mobile);
	}
	
	/**
	 * 根据手机号查找
	 */
	public List<User> findFund() {
		return User.me.find("select * from user where is_fund='1' and id<>1");
	}

	/**
	 * 根据编码查找
	 */
	public User findByCode(String code) {
		return User.me.findFirst("select * from user where code=?",code);
	}

	/**
	 * 登陆
	 */
	public User checkLogin(String mobile, String password) {
		return User.me.findFirst("select * from user where mobile=? and password=?",mobile,password);
	}

	/**
	 * 手机号是否存在
	 */
	public boolean isExistMobile(String mobile) {
		return User.me.findFirst("select id from user where mobile=?",mobile)!=null; 
	}

	/**
	 * 总人数
	 */
	public long total() {
		User u = User.me.findFirst("select count(id) as total from user");
		return u.getLong("total")!=null && u.getLong("total")>0 ? u.getLong("total") : 0;
	}
	
	/**
	 * 统计用户所有资产
	 * @throws Exception 
	 */
	public Map<String, Double> sumAllAssets(int userId) throws Exception {
		 
		Map<String, Double> assets = new HashMap<String, Double>();

		// 待收本金 & 待收利息
		Repay item = Repay.me.findFirst("select sum(amount) as amount, sum(interest+jxq+plus) as interest from repay where user_id=? and status='process'",userId);
		assets.put("amount", Money.get(item.getDouble("amount")));
		assets.put("interest", Money.get(item.getDouble("interest")));
		
		// 累计投资金额 & 累计投资收益
		item = Repay.me.findFirst("select sum(amount) as amount, sum(interest) as interest, sum(jxq) as jxq, sum(plus) as plus from repay where user_id=?",userId);
		assets.put("amount2", Money.get(item.getDouble("amount")));
		double jxq = Money.get(item.getDouble("jxq"));
		double plus = Money.get(item.getDouble("plus"));
		double interests = Money.get(item.getDouble("interest"));
		assets.put("jxq", jxq);
		assets.put("plus", plus);
		assets.put("interests", interests);
		assets.put("interest2", Money.add(jxq, plus, interests));
		
		// 累计体验金
		CouponLog couponLog = CouponLog.me.findFirst("select sum(amount) as total from coupon_log where user_id=? and type='tyj' and is_show='1' and status='normal' ",userId);
		assets.put("total_tyj", Money.get(couponLog.getDouble("total")));
		
		return assets;
	}
	
	/**
	 * 统计用户所有资产明细
	 * @throws Exception 
	 */
	public double sumAllAssetsDetail(int userId, String amount) throws Exception {
		 
		// 代收收益+代收本金
		Repay item = Repay.me.findFirst("select sum(amount) as total from repay where user_id=? and status='process'",userId);
		double ready = item.getDouble("total")!=null && item.getDouble("total")>0 ? item.getDouble("total") : 0;
		
		return Money.add(Double.valueOf(amount), ready);
	}
	
	/**
	 * 统计用户所有已收收益
	 */
	public double sumAllBenefit(int userId) {
		Repay item = Repay.me.findFirst("select sum(amount) as total from repay where user_id=? and status='success'",userId);
		return item.getDouble("total")!=null && item.getDouble("total")>0 ? item.getDouble("total") : 0;
	}

	/**
	 * 统计用户昨日收益
	 */
	public double sumYesterdayBenefit(int userId) {
		List<Trade> list = trade.findByUser(1, 999, userId, BidStatus.REPAYING).getList();
		double yesterday = 0.0;
		for(Trade t : list){
			if(t.getDate("invest_start_time")!=null) {
				Date create = t.getDate("invest_start_time");
				Date yes = DateUtil.parse(DateUtil.adjust(new Date(), -1, DateUtil.DATE_DEFAULT_FORMAT)+" 24:00:00");
				if(create.compareTo(yes)<0){
					yesterday += Money.div(Money.add(t.getTargetPlusAmount(), Money.add(t.getTargetAmount(), t.getTargetJxqAmount())), t.getDayLimit());
				}
			}
		}
		return Money.format(yesterday);
	}

	/**
	 * 分页信息
	 * @param map 
	 * @return 
	 */
	public Page<User> list(int page, int size, Map<String, String> map) {
		return User.me.paginate(page, size, buildSql("user",Arrays.asList("is_agent","is_fund", "agent_id", "is_bind_bank_card", "create_time", "bind_card_time", "real_name", "mobile", "referee"),map," and mobile<>'18867643093' order by create_time desc"));
	}

	/**
	 * 获取好友列表
	 * @param map 
	 * @return
	 */
	public Page<User> findFriends(int page, int size, int userId) {
		return User.me.paginate(page, size, "select id,mobile,real_name,create_time ", "FROM user WHERE referee=? ORDER BY create_time DESC ", userId);
	}

	/**
	 * 更改手机号后，刷新新手机号
	 * @param mobile
	 * @param mobile2
	 */
	public void refreshMobile(String mobile, String mobile2) {
		List<String> tables = Arrays.asList(new String[] {"token","withdraw","assets_log","deposit","bank_card","coupon_log","logger","repay","staff","trade","user_referee","visit"});
		for(String t : tables) {
			Db.update("update "+t+" set mobile=? where mobile=?",mobile2,mobile);
		}
	}

	public void migrate(User u1, User u2) {
		Db.update("update user set agent_id=? where agent_id=?",u2.getId(),u1.getId());
	}
}
